package io.renren.modules.job.task;

import io.renren.modules.mvs.dto.TicketDto;
import io.renren.modules.mvs.entity.TicketEntity;
import io.renren.modules.mvs.service.TicketService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

import static io.renren.common.utils.MvsUtils.calculateOverDueFee;

@Component("updateOverdueFeTask")
@Log4j2
public class UpdateOverdueFeeTask implements ITask {
    @Autowired
    private TicketService ticketService;

    @Override
    public void run(String params) {
        log.info("开始更新滞纳金数据......");
        List<TicketDto> ticketDtoList = ticketService.getTicketDtoList();
        List<TicketEntity> ticketList = new ArrayList<>();
        for (TicketDto ticketDto : ticketDtoList) {
            TicketEntity ticket = new TicketEntity();
            ticket.setId(ticketDto.getId());
            // 违章天数
            LocalDate localDate = ticketDto.getViolationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            long dayNumber = ChronoUnit.DAYS.between(localDate, LocalDate.now());
            ticket.setViolationDay((int) (dayNumber < 0 ? 0 : dayNumber));
            // 滞纳金
            BigDecimal overdueFee = calculateOverDueFee(ticketDto.getViolationDeadline(), ticketDto.getFineAmount());
            BigDecimal originOverdueFee = ticketDto.getOverdueFee();
            ticket.setOverdueFee(overdueFee);
            // 待缴滞纳金
            ticket.setWaitOverdueFee(overdueFee.subtract(originOverdueFee.subtract(ticketDto.getWaitOverdueFee())));
            ticketList.add(ticket);
        }
        ticketService.updateBatchById(ticketList);
    }
}
